package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IProductDao;
import com.seal.dto.ProductDto;
import com.seal.model.Product;

@Repository("productDaoImpl")
@SuppressWarnings("unchecked")
public class ProductDaoImpl extends BaseDaoImpl implements IProductDao{

	public void addProduct(Product ca) throws Exception {
		this.save(ca);
	}

	public void updateProduct(Product ca) throws Exception {
		this.update(ca);
	}
	
	public void deleteProduct(Product ca) throws Exception {
		this.delete(ca);
	}
	
	public Product getProductById(Long id) throws Exception {
		return (Product) this.select(Product.class, id);
	}
	
	public List<Product> getAllProduct(ProductDto productDto, Page page)throws Exception {
		StringBuffer hql=new StringBuffer("from Product t where 1=1");
		if (null != productDto.getFromDate()
				&& !"".equals(productDto.getFromDate())) {
			hql.append(" and t.startDate <= :fromDate");
		}
		
		if (null != productDto.getToDate()
				&& !"".equals(productDto.getToDate())) {
			hql.append(" and t.endDate >= :toDate");
		}
		
		if (null != productDto.getStatus()) {
			hql.append(" and t.status = :status");
		}
		
		if (null != productDto.getProductName()
				&& !"".equals(productDto.getProductName().trim())) {
			productDto.setProductName("%"+productDto.getProductName().trim()+"%");
			hql.append(" and t.productName like :productName");
		}

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(productDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql="select count(t) "+hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(productDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}
		
		return query.list();
	}
	
}
